package com.ws.shop.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.ws.shop.bean.Page;
import com.ws.shop.dao.CategoryDao;
import com.ws.shop.entity.Category;

@Repository(value="categoryDao")
public class CategoryDaoImpl extends BaseDaoImpl implements CategoryDao {

	final String findAllCategoryList = "select id,categoryname,state from jvf_category order by id";
	public List<Category> findAllCategoryList() {
		return this.query(findAllCategoryList, new ResultSetExtractor<List<Category>>(){
			public List<Category> extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				List<Category> list = new LinkedList<Category>();
				Category c = null;
				while(rs.next()){
					c = new Category();
					c.setId(rs.getInt(1));
					c.setCategoryname(rs.getString(2));
					c.setState(rs.getInt(3));
					list.add(c);
				}
				return list;
			}
		});
	}
	
	final String save_category = "insert into jvf_category(categoryname,state) values(?,?)";
	final String update_category = "update jvf_category set categoryname=?,state=? where id=?";
	public void saveOrUpdate(Category category) {
		if(category.getId() == 0)
			this.update(save_category, category.getCategoryname(),category.getState());
		else
			this.update(update_category, category.getCategoryname(),category.getState(),category.getId());
	}
	
	/**
	 * 查询商品类型
	 * @param id
	 * @return
	 */
	public Category getCategory(final int id){
		String s = "select  categoryname,state  from  jvf_category where id = " + id;
		return query(s, new ResultSetExtractor<Category>(){
			public Category extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if(rs.next()){
					Category c = new Category();
					c = new Category();
					c.setId(id);
					c.setCategoryname(rs.getString(1));
					c.setState(rs.getInt(2));
					return c;
				}
				return null;
			}
		});
	}

	final String findCategoryListByPage_count = "select count(1) from jvf_category";
	final String findCategoryListByPage_list = "select id,categoryname,state from jvf_category";
	final String findCategoryListByPage_order = " order by id";
	public Page findCategoryListByPage(int pageno, int pagesize,
			String categoryname) {
		StringBuilder query = new StringBuilder(" where 1=1");
		if(categoryname != null){
			query.append(" and categoryname='").append(categoryname).append("'");
		}
		return findPage(pageno,pagesize,new StringBuilder(findCategoryListByPage_count).append(query).toString()
				,new StringBuilder(findCategoryListByPage_list).append(query).append(findCategoryListByPage_order));
	}
	
}
